#include "BlockQueue.hpp"
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include "Task.hpp"
#include "RingQueue.hpp"
struct threaddata
{
    RingQueue<int> *bq;
    std::string msg;
};
void *producer(void *arg)
{

    // RingQueue<int> *bq = static_cast<RingQueue<int> *>(arg);
    struct threaddata *td = static_cast<struct threaddata *>(arg);

    std::cout << "Producer is producing items..." << std::endl;
    // 生产逻辑省略
    int data = 1;
    while (true)
    {
        sleep(1); // 模拟生产耗时
        std::cout << td->msg << "### " << "生产任务:" << std::endl;

        td->bq->Equeue(data);
        data++;
    }
    return nullptr;
}
void *consumer(void *arg)
{

    // RingQueue<int> *bq = static_cast<RingQueue<int> *>(arg);
    struct threaddata *td = static_cast<struct threaddata *>(arg);
    std::cout << "Consumer is consuming items..." << std::endl;
    // 消费逻辑省略
    while (true)
    {
        sleep(2); // 模拟消费耗时
        int t = 0;
        td->bq->Pop(&t);
        std::cout << td->msg << "### " << " 消费一个数据: " << t << std::endl;
    }
    return nullptr;
}

int main()
{
    RingQueue<int> *bq = new RingQueue<int>(); // 申请阻塞队列

    // 构建生产消费
    pthread_t p1[3], c1[2];

    struct threaddata *td = new threaddata();
    td->msg = "cthread-1";
    td->bq = bq;
    pthread_create(c1, nullptr, consumer, td);

    struct threaddata *td2 = new threaddata();
    td2->msg = "cthread-2";
    td2->bq = bq;
    pthread_create(c1 + 1, nullptr, consumer, td2);

    struct threaddata *tdp1 = new threaddata();
    tdp1->msg = "pthread-1";
    tdp1->bq = bq;
    pthread_create(p1, nullptr, producer, tdp1);

    struct threaddata *tdp2 = new threaddata();
    tdp2->msg = "pthread-2";
    tdp2->bq = bq;
    pthread_create(p1 + 1, nullptr, producer, tdp2);

    struct threaddata *tdp3 = new threaddata();
    tdp3->msg = "pthread-3";
    tdp3->bq = bq;
    pthread_create(p1 + 2, nullptr, producer, tdp3);

    pthread_join(p1[0], nullptr);
    pthread_join(p1[1], nullptr);
    pthread_join(p1[2], nullptr);

    pthread_join(c1[0], nullptr);
    pthread_join(c1[1], nullptr);
    return 0;
}